package rs.etf.kdp.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

/**
 * @author Djordje Vukovic
 * @version 1.0
 * @created 16-May-2011 4:59:09 PM
 */
public class RequestedJobsCollection {

	private FileReader list;
	private List<RememberedJob> newJobs;
	
	/**
	 * @wbp.parser.entryPoint
	 */
	public RequestedJobsCollection(){
		try {
			list = new FileReader("res/previousjobs.job");
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(null, "Unable to retrive list of previous jobs");
		}
		
		newJobs = new ArrayList<RememberedJob>();
		
	}

	public void addNewJob(RememberedJob newJob){
		newJobs.add(newJob);
	}
	
	public void setNewJobsStatus(long id, String status)
	{
		for(RememberedJob j : newJobs)
		{
			if(j.getJobId()==id)
			{
				j.setJobStatus(status);
				return;
			}
		}
	}

	public List<RememberedJob> getFromFile(){
		List<RememberedJob> jobs = new ArrayList<RememberedJob>();
		BufferedReader reader = new BufferedReader(list);
		String line;
		
		try {
			while((line = reader.readLine())!=null)
			{
				String[] tokenized = line.split(" ");
				long id = Long.parseLong(tokenized[0]);
				RememberedJob newJob = new RememberedJob(id, tokenized[1], tokenized[2]);
				jobs.add(newJob);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jobs;

	}

	public void saveToFile(){
		
		FileWriter writer;
		
		try {
			writer  = new FileWriter("res/previousjobs.job", true);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		
		BufferedWriter bwriter = new BufferedWriter(writer);
		
		for(RememberedJob job : newJobs)
		{
			String lineInFile = job.getJobId() + " " + job.getJobName() + " " + job.getJobStatus();
			try {
				bwriter.write(lineInFile + "\n");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			bwriter.close();
		} catch (IOException e) {
			System.out.println("\nUnable to write file while saving requested jobs");
		}
		newJobs.clear();
	}

	public List<RememberedJob> getNewJobs() {
		return newJobs;
	}


}